//
//  CNDetailSearchViewController.m
//  BeeQuick_19
//
//  Created by kimi on 16/9/23.
//  Copyright © 2016年 CN Team. All rights reserved.
//

#import "CNDetailSearchViewController.h"
#import "CNHotSearchModel.h"
#import "CNSearchSelectView.h"
#import "CNSearchResultFlowLayout.h"
#import "CNSearchResultCollectionViewCell.h"
#import "CNRefreshHeaderView.h"


static NSString * const reuseIdentifier = @"cell";

@interface CNDetailSearchViewController ()<UISearchBarDelegate,UICollectionViewDataSource,UICollectionViewDelegate,CNSearchResultCollectionViewCellDelegate,CAAnimationDelegate>

//获取搜索栏
@property (nonatomic,weak)UISearchBar *searchBar;
//模型数组
@property (nonatomic,strong) NSArray <CNHotSearchModel *>*modelArray;

@property (nonatomic,weak)UICollectionView *collectionView;
//无数据图片
@property (nonatomic,strong)UIImageView *noDataImageView;

/**
 当前页码
 */
@property (nonatomic, assign) NSInteger currentPage;
//记录手势
@property (nonatomic,weak) UITapGestureRecognizer *tap;
//显示的数组
@property (nonatomic,strong) NSArray <CNHotSearchModel *>*showModelArray;

//第二次筛选的数组
@property (nonatomic,strong) NSArray <CNHotSearchModel *>*secondShowModelArray;

//判断位于哪个选项
@property (nonatomic,assign) SortType sortType;

//中间的排序View
@property (nonatomic,weak) CNSearchSelectView *searchSelectView;


@end

@implementation CNDetailSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    
    [self setupUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupUI{
    //设置搜索栏
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barBuutonItemWithTarget:self action:@selector(backButtonClick) icon:@"v2_goback" highlighticon:@"v2_goback"];
    
    UISearchBar *searchBar = [UISearchBar new];
    searchBar.placeholder = @"请输入搜索内容";
    searchBar.delegate = self;
    self.searchBar = searchBar;
    self.navigationItem.titleView = searchBar;
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.view.userInteractionEnabled =YES;
    
    //设置默认显示上一个页面输入数据
    searchBar.text = self.searchInfoString;
    //添加搜索栏右侧button
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchBtnClick)];
    
    //设置颜色
    item.tintColor = [UIColor blueColor];
    
    self.navigationItem.rightBarButtonItem = item;
    //设置字体颜色
    
    //添加背景，产生1像素的线
    UIView *backView = [UIView new];
    
    backView.backgroundColor = [UIColor colorWithHex:0xACADAF];
    [self.view addSubview:backView];
    
    //布局
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(22);
        make.left.right.offset(0);
        make.height.offset(43);
    }];
    
    
    //添加中间的view
    CNSearchSelectView *searchSelectView = [CNSearchSelectView searchSelectNavView];
    self.searchSelectView = searchSelectView;

    [self.view addSubview:searchSelectView];
    
    //自动布局
    [searchSelectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backView.mas_bottom);
        make.left.right.offset(0);
        make.height.offset(44);
    }];
    
    //添加collectionView
    //1.创建流水布局
    CNSearchResultFlowLayout *layout = [[CNSearchResultFlowLayout alloc]init];
    //2.创建集合视图
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    
    //注册单元格
    [collectionView registerNib:[UINib nibWithNibName:@"CNSearchResultCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    // 取消指示器(滚动条)
    collectionView.showsVerticalScrollIndicator = NO;
    
    // 设置背景颜色
    collectionView.backgroundColor = [UIColor colorWithHex:0xEFEFEF];
    // 添加视图
    [self.view addSubview:collectionView];
    //添加数据源和代理
    collectionView.dataSource = self;
    collectionView.delegate = self;
    
    self.collectionView = collectionView;
    
    //设置自动布局
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(searchSelectView.mas_bottom);
        make.left.right.offset(0);
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
    }];
    
    //添加清点手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tipGestureRecognizer:)];
    
    self.tap = tap;
    
    [collectionView addGestureRecognizer:tap];

    //添加刷新模块
    
    [self setupRefresh];
    
    //排序
    __weak CNDetailSearchViewController *weakSelf = self;
    
    //回调block
    searchSelectView.sortBlock = ^(SortType sortType){
        
        //判断如果没有数据直接返回
        if (weakSelf.showModelArray.count == 0) {
            return;
        }
        //告诉控制器，我选择了哪个选项
        weakSelf.sortType = sortType;
        //创建数组
        NSMutableArray *array = [NSMutableArray arrayWithArray:weakSelf.showModelArray];
        //排序
        array = [weakSelf sortArray:array type:sortType];
        //重新给数组赋值，刷新
        weakSelf.secondShowModelArray = [NSArray arrayWithArray:array.copy];
        weakSelf.showModelArray = [NSArray arrayWithArray:array.copy];
        [weakSelf.collectionView reloadData];
        //记得将值改回来
        weakSelf.showModelArray = weakSelf.secondShowModelArray;
    };
}

#pragma mark - 排序
//排序方法
- (NSMutableArray *)sortArray:(NSMutableArray *)array type:(SortType )type{
    
    switch (type) {
            //综合排序
        case kSynthesizeSort:
            
            [array sortUsingComparator:^NSComparisonResult(CNHotSearchModel *  _Nonnull obj1, CNHotSearchModel *  _Nonnull obj2) {
                
                if (obj1.sort.integerValue < obj2.sort.integerValue) {
                    return NSOrderedAscending;
                }
                return NSOrderedDescending;
            }];
            break;
        case kPriceSort:
            [array sortUsingComparator:^NSComparisonResult(CNHotSearchModel *  _Nonnull obj1, CNHotSearchModel *  _Nonnull obj2) {
                
                if (obj1.price.floatValue < obj2.price.floatValue) {
                    return NSOrderedAscending;
                }
                return NSOrderedDescending;
            }];
            
            break;
        case kSalesSort:
            [array sortUsingComparator:^NSComparisonResult(CNHotSearchModel *  _Nonnull obj1, CNHotSearchModel *  _Nonnull obj2) {
                
                if (obj1.number.integerValue > obj2.number.integerValue) {
                    return NSOrderedAscending;
                }
                return NSOrderedDescending;
            }];
            
            break;
        default:
            break;
    }
    return array;
}


- (void)tipGestureRecognizer:(UIGestureRecognizer *)tap{
    
    [self.searchBar resignFirstResponder];
}


#pragma mark - 刷新框架
- (void)setupRefresh
{
    //1.添加下拉刷新
    
    self.collectionView.mj_header=[CNRefreshHeaderView headerWithRefreshingBlock:^{
        [self loadNewDeals];
    }];

    //2.自动刷新
    [self.collectionView.mj_header beginRefreshing];
    //3.添加上啦刷新
//    self.collectionView.mj_footer = [CNRefreshHeaderView footerWithRefreshingBlock:^{
////        [self loadMoreDeals];
//    }];
    //4.开始隐藏底部刷新
    self.collectionView.mj_footer.hidden = YES;
}

#pragma mark 下拉刷新
- (void)loadNewDeals
{
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    //当第一的时候加载
    [self loadData:^(NSDictionary *response) {
            NSDictionary *dict = response[@"data"];
            self.modelArray = [NSArray yy_modelArrayWithClass:[CNHotSearchModel class] json:dict];
             self.modelArray =  [[SQLiteManager sharedSQLiteManager] getValueWith:self.modelArray];
            self.showModelArray = self.modelArray.copy;
  
        dispatch_group_leave(group);
    }];
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        if (self.searchFlag) {
                //去搜索
                [self searchInfo:self.searchInfoString];
                //更改flag
                self.searchFlag = false;
        }else{
            //去搜索
            [self searchInfo:self.searchInfoString];
        }
        //加载完毕后挺住刷新窗口
        [self.collectionView.mj_header endRefreshing];
        [self loadAlertView];
    });

}


#pragma mark - 返回按钮
- (void)backButtonClick
{
    //回调搜索数据
    if (self.searchInfoBlock) {
        self.searchInfoBlock(self.searchInfoString);
    }
    
    [self.navigationController popViewControllerAnimated:true];
}



#pragma mark - 搜索按钮
- (void)searchBtnClick{
    
    [self.searchBar endEditing:true];
    
    [self searchInfo:self.searchInfoString];

}

#pragma mark - 搜索数据
- (void)searchInfo:(NSString *)searchInfo{
    
    if (searchInfo == nil || [searchInfo isEqualToString:@""]) {
        self.showModelArray = [NSArray array];
        [self.collectionView reloadData];
        return;
    }
    
    //1.首先名字name，只搜索这个
    NSMutableArray *resultArray = [NSMutableArray array];
    
    for (CNHotSearchModel *model in self.modelArray) {
        if ([model.name containsString:searchInfo]) {
            [resultArray addObject:model];
            NSLog(@"%@",model.name);
        }
    }
    
//    self.showModelArray = [NSArray arrayWithArray:resultArray.copy];
    
    //根据所选内容设置关联
    [self.searchSelectView changeViewSelectWithType:self.sortType];
    //判断位于哪个排序？根据所选位置排序
    self.showModelArray = [self sortArray:resultArray type:self.sortType];
    
    [self.collectionView reloadData];

}

#pragma mark - 加载数据
- (void)loadData:(void(^)(NSDictionary *response))completion{
    
    //1.组包参数
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setValue:@"8" forKey:@"call"];
    
    //网络获取数据
    [[CNHTTPSessionManager sharedManager] request:CNHttpMethodPost componentUrlString:@"promotion.json.php" parameters:param completion:^(id response, NSError *error) {
        if (error != nil || response == nil ) {
            NSLog(@"请求错误%@",error);
            return;
        }else{

             completion(response);
        }
    }];
    
    
}

#pragma mark 提示框
- (void)loadAlertView{
    
    if (self.showModelArray.count != 0) {
        return;
    }
    UILabel * tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
    tipLabel.center = self.collectionView.center;
    [tipLabel setText:@"没有数据更新"];
    tipLabel.backgroundColor = [UIColor blackColor];
    tipLabel.layer.cornerRadius = 5;
    tipLabel.layer.masksToBounds = YES;
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:tipLabel];
    [UIView animateWithDuration:2.0 animations:^{
        tipLabel.alpha = 0.0;
    } completion:^(BOOL finished) {
        [tipLabel removeFromSuperview];
    }];
}
#pragma mark - collectionDateSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    self.noDataImageView.hidden = self.showModelArray.count != 0;
    
    return self.showModelArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CNSearchResultCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    __weak CNDetailSearchViewController *weakSelf = self;
    cell.incCountBlock = ^(){
        
        weakSelf.showModelArray[indexPath.item].count++;
        NSLog(@"%zd",weakSelf.showModelArray[indexPath.item].pageCount);
        [weakSelf.collectionView reloadData];
        
    };
    
    cell.desCountBlock = ^(){
        weakSelf.showModelArray[indexPath.item].count--;
        NSLog(@"%zd",weakSelf.showModelArray[indexPath.item].pageCount);
        [weakSelf.collectionView reloadData];
    };
    
    cell.delegate = self;
    cell.hotSearchModel = self.showModelArray[indexPath.item];
    
    return cell;
}



#pragma mark - 懒加载无数据图片
- (UIImageView *)noDataImageView
{
    if (!_noDataImageView) {
        _noDataImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_deals_empty"]];
        
        [self.collectionView addSubview:_noDataImageView];
        
        [_noDataImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.collectionView);
        }];
    }
    return _noDataImageView;
}


#pragma mark - 移除手势
-(void)viewDidDisappear:(BOOL)animated
{
    [self.collectionView removeGestureRecognizer:self.tap];
}

#pragma mark - 添加动画代理
- (void)shopDetailOrderFoodCell:(CNSearchResultCollectionViewCell*)shopDetailOrderFoodCell didClickAddButton:(UIButton*)addButton
{
    // 转坐标  cell -> self.view
    //    CGPoint start = [shopDetailOrderFoodCell convertPoint:addButton.center toView:[UIApplication sharedApplication].keyWindow];
    UIImageView *selecedImageView = shopDetailOrderFoodCell.img;
    
    CGPoint start = [shopDetailOrderFoodCell convertPoint:selecedImageView.center toView:self.view.window];
    
    
    // 1.做什么动画
    CAAnimationGroup* group = [[CAAnimationGroup alloc] init];
    // MARK:进入购物车路径动画
    CAKeyframeAnimation* anim = [[CAKeyframeAnimation alloc] init];
    // 修改位置
    anim.keyPath = @"position";
    
    //    // 设置时间
    //    anim.duration = 2;
    
    //    // 不让核心动画回来
    //    anim.fillMode = kCAFillModeForwards;
    //    anim.removedOnCompletion = NO;
    
    // 画曲线
    UIBezierPath* path = [UIBezierPath bezierPath];
    [path moveToPoint:start];
    
    //转化坐标系
    // 转坐标 购物车 -> self.view
    
    CGPoint end = CGPointMake([UIScreen mainScreen].bounds.size.width / 4 * 3 -([UIScreen mainScreen].bounds.size.width / 4 /2), [UIScreen mainScreen].bounds.size.height - 22);
    
//    CGPoint end = [self.tabBarController viewControllers][2].view.center;
    
//    NSLog(@"%f",end);
    
    [path addQuadCurveToPoint:end  controlPoint:CGPointMake(start.x+100, start.y-200)];
    // 设置路径
    anim.path = path.CGPath;
    
    
    //设置代理（隐式代理，不遵守协议）走销毁方法
    
    // 创建小红点
    UIImageView* redPointView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, (self.view.bounds.size.width-30) / 2, 160)];
    redPointView.image = selecedImageView.image.copy;
    redPointView.center = start;
    [self.view.window addSubview:redPointView];
    
    
    
    
    // MARK:自旋转动画
    // 1.创建动画对象(做什么动画)
    CABasicAnimation* anim1 = [[CABasicAnimation alloc] init];
    
    // 2.修改动画的属性(怎么做动画)
    // 修改的属性
    anim1.keyPath = @"transform.rotation";
    
    // 累加
    anim1.byValue = @(M_PI * 2 * 3); // 一圈
    
    
    //缩放
    CABasicAnimation *anim2 = [CABasicAnimation animation];
    anim2.toValue = [NSValue valueWithCGSize:CGSizeMake(0.2, 0.2)];
    anim2.keyPath = @"transform.scale";
    anim2.removedOnCompletion = YES;
    anim2.fillMode = kCAFillModeForwards;
    
    
    
    group.delegate = self;
    
    // MARK:添加核心动画
    group.animations = @[ anim,anim1,anim2 ];
    // 设置时间
    group.duration = 1;
    //    // 设置重复次数
    //    group.repeatCount = MAXFLOAT;
    //设置的时候 写在添加核心动画之前
    [group setValue:redPointView forKey:@"redPointView"];
    //    [redPointView.layer addAnimation:anim forKey:nil];
    [redPointView.layer addAnimation:group forKey:nil];

}


#pragma mark -UISearchBarDelegate


-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    //清除上一次数据
    self.searchBar.text = @"";
    self.searchInfoString = @"";
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    self.searchInfoString = searchBar.text;
}


#pragma mark - 核心动画完成
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    //在动画结束的时候,通过不同的anim对象,取同样的key.就可以获取到每次做动画的iamgeView
    UIView *view = [anim valueForKey:@"redPointView"];
    NSLog(@"%@",view);
    [view removeFromSuperview];
}


@end
